package sc.tcp.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import sc.tcp.TCPGateway;
import sc.udp.UDPGateway;

public abstract class TCPGatewayImpl implements TCPGateway {

	private Object readMutex = new Object();

	private Object writeMutex = new Object();

	protected Socket socket;

	public void startTCPGateway(UDPGateway udpGW) {
		Thread receiver = new Thread(new TCPReceiver(udpGW, this));
		receiver.start();
	}

	public byte[] read() {
		synchronized (readMutex) {
			byte[] newData = null;

			try {
				InputStream in = socket.getInputStream();

				byte[] lenByte = new byte[2];
				in.read(lenByte);
				int len = (((int)lenByte[0])&0x000000ff)*256 + (((int)lenByte[1])&0x000000ff);
				len += 2; // PORT

				newData = new byte[len];
				for (int i = 0; i < len; i++) {
					newData[i] = (byte) in.read();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}

			return newData;
		}
	}

	public synchronized void write(byte[] data) {
		synchronized (writeMutex) {
			try {
				OutputStream out = socket.getOutputStream();
				out.write(data);
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
